import type { INews, NewsType } from "@/types";
import { nanoid } from "nanoid";
import { defineStore } from "pinia";
import { onMounted, ref } from "vue";

export const useNewsStore = defineStore('news', () => {

  const news = ref<INews[]>([])

  function addNews(newsItem: INews) {
    news.value.push(newsItem)
  }

  const newsType = ref<NewsType[]>([
    { id: nanoid(), type: '天气预报' },
    { id: nanoid(), type: '娱乐新闻' },
    { id: nanoid(), type: '体育新闻' },
  ]
  )

  function getNewsByType(newsType: string = '') {
    if (newsType === '') {
      return news.value
    } else {
      return news.value.filter(item => item.type === newsType)
    }
  }

  function getNewsById(id: string) {
    const theNews = news.value.find(item => item.id === id)
    console.log('get news by id: ', id, " the news is ", theNews)
    return theNews
  }


  onMounted(() => {
    addNews({
      id: nanoid(),
      type: '天气预报',
      title: '云城未来将迎来...',
      author: '云城天气',
      express: 'South Express',
      content: '一场百年不遇的大雨，请注意提前准备物资和注意安全',
      publishedDate: new Date()
    })

    addNews({
      id: nanoid(),
      type: '天气预报',
      title: '晴天一霹雳...',
      author: '雷城天气',
      express: 'Thounder Express',
      content: '不是爆炸，是夏天的雷声，不用害怕，不在在树下等逗留',
      publishedDate: new Date()
    })

    addNews({
      id: nanoid(),
      type: '娱乐新闻',
      title: '刘亦菲官宣',
      author: '闲小喵',
      express: '',
      content: '刘亦菲官宣了吗？我怎么不知道',
      publishedDate: new Date()

    })

    addNews({
      id: nanoid(),
      type: '体育新闻',
      title: 'CBA赛季冠军',
      author: 'CBA',
      express: '',
      content: 'CBA赛季冠军是谁？',
      publishedDate: new Date()
    })

    console.log(news.value)
  })


  return { news, newsType, addNews, getNews: getNewsByType, getNewsById }
})
